package com.eip.zd.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eip.zd.entity.Price;
import com.eip.zd.exception.CustomException;
import com.eip.zd.mapper.PriceMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;

@Service
public class PriceService {
    @Resource
    private PriceMapper priceMapper;

    public List<Price> getPriceList(String keyword) {
        return priceMapper.getPriceList(keyword);
    }

    public void add(Price price) {
        if (StrUtil.hasEmpty(price.getCustId())) {
            throw new CustomException(500, "客户编号不能为空");
        }
        if (StrUtil.hasEmpty(price.getStartDate())) {
            String format = DateUtil.format(new Date(), "yyyy-MM-dd");
            price.setStartDate(format);
        }
        QueryWrapper<Price> wrapper = new QueryWrapper<>();
        wrapper.eq("cust_id", price.getCustId());
        wrapper.eq("prod_id", price.getProdId());
        Price one = priceMapper.selectOne(wrapper);
        if (one != null) {
            throw new CustomException(500, "该客户对应的产品已存在价格");
        }
        priceMapper.insert(price);
    }

    public void update(Price price) {
        if (StrUtil.hasEmpty(price.getStartDate())) {
            String format = DateUtil.format(new Date(), "yyyy-MM-dd");
            price.setStartDate(format);
        }
        price.setPrice(price.getPrice().setScale(2, RoundingMode.HALF_UP));
        Price source = priceMapper.selectById(price.getId());
        if (source.getPrice().equals(price.getPrice())) {
            priceMapper.updateById(price);
        } else {
            priceMapper.deleteById(price.getId());
            price.setId(null);
            priceMapper.insert(price);
        }
    }

    public void remove(Long id) {
        Price price = priceMapper.selectById(id);
        price.setIfUse(2);
        priceMapper.updateById(price);
        priceMapper.deleteById(id);
    }

    public void ifUse(Long id) {
        Price price = priceMapper.selectById(id);
        if (price.getIfUse() == 1) {
            price.setIfUse(2);
        } else {
            price.setIfUse(1);
        }
        priceMapper.updateById(price);
    }

    public List<Price> getHisPriceList(String custId) {
        return priceMapper.getHisPriceList(custId);
    }
}
